package com.shop.service.impl;

import com.alipay.api.domain.Shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.common.TokenUtil;
import com.shop.common.result.Result;
import com.shop.common.result.util.ResultModel;
import com.shop.entity.ShopDo;
import com.shop.entity.ShopWarehoseRelationDo;
import com.shop.entity.WarehouseInfoDo;
import com.shop.mapper.ShopDoMapper;
import com.shop.mapper.ShopWarehoseRelationDoMapper;
import com.shop.mapper.WarehouseInfoDoMapper;
import com.shop.service.WarehouseInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.vo.seller.SelectWarehouseInfoByShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 仓库表 服务实现类
 * </p>
 *
 * @author 靳 旺
 * @since 2021-01-29
 */
@Service
public class WarehouseInfoServiceImpl extends ServiceImpl<WarehouseInfoDoMapper, WarehouseInfoDo> implements WarehouseInfoService {

    @Autowired
    private ShopDoMapper shopDoMapper;

    @Autowired
    private ShopWarehoseRelationDoMapper shopWarehoseRelationDoMapper;

    @Override
    public ResultModel selectWarehouseInfoByShop(SelectWarehouseInfoByShopVo selectWarehouseInfoByShopVo) throws Exception {
        QueryWrapper<ShopDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fk_client_id", TokenUtil.getUserId());
        ShopDo shopDo = shopDoMapper.selectOne(queryWrapper);
        Assert.notNull(shopDo, "您还没有开店铺");

        QueryWrapper<ShopWarehoseRelationDo> shopWarehoseRelationDoQueryWrapper = new QueryWrapper<>();
        shopWarehoseRelationDoQueryWrapper.eq("fk_shop_id", shopDo.getPkShopId());
        List<ShopWarehoseRelationDo> shopWarehoseRelationDoList = shopWarehoseRelationDoMapper.selectList(shopWarehoseRelationDoQueryWrapper);
        if (shopWarehoseRelationDoList.size() <= 0) throw new Exception("您还没有仓库！");
        List<Long> warehoseIds = shopWarehoseRelationDoList.stream().map(ShopWarehoseRelationDo::getFkWarehoseInfoId).collect(Collectors.toList());

        PageHelper.startPage(selectWarehouseInfoByShopVo.getPageIndex(),selectWarehouseInfoByShopVo.getPageSize());
        List<WarehouseInfoDo> warehouseInfoDos = baseMapper.selectBatchIds(warehoseIds);
        PageInfo<WarehouseInfoDo> warehouseInfoDoPageInfo = new PageInfo<>(warehouseInfoDos);
        return Result.successResultModel(warehouseInfoDoPageInfo);
    }
}
